#pragma once

#include <map>
#include <string>
#include "OSMutex.h"
#include "parser.h"
#include "rmParser.h"
#include "AsfParser.h"

using namespace std;


class ParserMgr
{
	class ParserData
	{
	public:
		ParserData(CString filename)
		{
            m_Parser = NULL;

            int nAt = filename.ReverseFind( '.' );
            if ( nAt >= 0 )
            {
                CString sExtName = filename.Mid( nAt + 1 );

                if ( sExtName.CompareNoCase( _T("rm") ) == 0 || sExtName.CompareNoCase( _T("rmvb") ) == 0 )
                {
                    m_Parser = new RmParser( filename );
                }
                else if ( sExtName.CompareNoCase( _T("wmv") ) == 0 ||
                    sExtName.CompareNoCase( _T("asf") ) == 0 || 
                    sExtName.CompareNoCase( _T("avi") ) == 0 ||
                    sExtName.CompareNoCase( _T("mpeg") ) == 0 ||
                    sExtName.CompareNoCase( _T("mpg") ) == 0 )
                {
                    m_Parser = new AsfParser( filename );
                }
            }

            BOOL ret  = m_Parser->Initialize();
            if(ret == FALSE) 
            {
                delete m_Parser;
                m_Parser = NULL;
            }

            m_Count = 1;
		}
		~ParserData()
		{
			if( m_Parser != NULL)
			{
				delete m_Parser;
			}
		}
		Parser* GetParser()
		{
			return m_Parser;
		}
		void Increase()
		{
			OSMutexLocker locker(&m_Locker);
			m_Count++;
		}
		void  Decrease()
		{
			OSMutexLocker locker(&m_Locker);
			m_Count--;
			if(m_Count == 0) 
			{
				if( m_Parser != NULL)
				{
					delete m_Parser;
					m_Parser = NULL;
				}
			}
		}
	private:
		OSMutex m_Locker;
		DWORD m_Count;
		Parser* m_Parser;
	};

public:
	ParserMgr();
	virtual ~ParserMgr();
	static ParserMgr* GetInstance()
	{
		if(m_ParserMgr==NULL)
		{
			m_ParserMgr = new ParserMgr();
		}
		return m_ParserMgr;
	};

public:
	Parser* GetParser(const char* v_FileName);
	BOOL FreeParser(const char* v_FileName);

//private:
	OSMutex m_Locker;
	static ParserMgr* m_ParserMgr;
	map<string,ParserData*> m_ParserList;
};

#define g_ParserMgr ParserMgr::m_ParserMgr
//extern ParserMgr g_ParserMgr;







